// mock/role.ts

// 模拟延迟
const waitTime = (time: number = 100) => {
    return new Promise((resolve) => {
        setTimeout(() => {
            resolve(true);
        }, time);
    });
};

// 生成模拟角色数据
const generateMockRoleData = (): any[] => {
    const data = [];

    for (let i = 1; i <= 50; i++) {
        data.push({
            id: `role_${i}`,
            roleName: `角色${i}`,
            roleCode: `ROLE_${i.toString().padStart(3, '0')}`,
            description: `这是角色 ${i} 的描述`,
            createTime: new Date(Date.now() - Math.floor(Math.random() * 10000000000)).toISOString(),
            updateTime: new Date(Date.now() - Math.floor(Math.random() * 5000000000)).toISOString(),
            // ... 其他可能的字段
        });
    }

    return data;
};

let mockRoles = generateMockRoleData();

export default {
    // 获取角色列表
    'GET /sys/role/list': async (req: any, res: any) => {
        await waitTime(500);

        const { current = 1, pageSize = 10, roleName, roleCode } = req.query;

        let filteredRoles = [...mockRoles];

        // 应用查询条件
        if (roleName) {
            filteredRoles = filteredRoles.filter(r => r.roleName.includes(roleName));
        }
        if (roleCode) {
            filteredRoles = filteredRoles.filter(r => r.roleCode.includes(roleCode));
        }

        // 分页
        const start = (parseInt(current) - 1) * parseInt(pageSize);
        const end = start + parseInt(pageSize);
        const paginatedData = filteredRoles.slice(start, end);

        res.json({
            success: true,
            message: '获取成功',
            result: {
                records: paginatedData,
                total: filteredRoles.length,
            },
        });
    },

    // 删除单个角色
    'DELETE /sys/role/delete': async (req: any, res: any) => {
        await waitTime(300);
        const { id } = req.query;

        const index = mockRoles.findIndex(r => r.id === id);
        if (index > -1) {
            mockRoles.splice(index, 1);
            res.json({
                success: true,
                message: '删除成功',
            });
        } else {
            res.status(404).json({
                success: false,
                message: '未找到角色',
            });
        }
    },

    // 批量删除角色
    'DELETE /sys/role/deleteBatch': async (req: any, res: any) => {
        await waitTime(500);
        const { ids } = req.query;
        const idList = ids.split(',');

        const initialLength = mockRoles.length;
        idList.forEach((id: string) => {
            const index = mockRoles.findIndex(r => r.id === id);
            if (index > -1) {
                mockRoles.splice(index, 1);
            }
        });
        const deletedCount = initialLength - mockRoles.length;

        res.json({
            success: deletedCount > 0,
            message: `成功删除 ${deletedCount} 条记录`,
        });
    },

    // 获取角色信息 (用于编辑/详情)
    'GET /sys/role/queryById/:id': async (req: any, res: any) => {
        await waitTime(300);
        const { id } = req.params;
        const role = mockRoles.find(r => r.id === id);

        if (role) {
            res.json({
                success: true,
                message: '获取成功',
                result: role,
            });
        } else {
            res.status(404).json({
                success: false,
                message: '未找到角色',
            });
        }
    },

    // 添加角色
    'POST /sys/role/add': async (req: any, res: any) => {
        await waitTime(500);
        const data = req.body;

        // 检查唯一性 (Mock)
        if (mockRoles.some(r => r.roleCode === data.roleCode)) {
            res.status(400).json({
                success: false,
                message: '角色编码已存在',
            });
            return;
        }

        const newRole = {
            ...data,
            id: `role_${mockRoles.length + 1}`, // Mock ID 生成
            createTime: new Date().toISOString(),
            updateTime: new Date().toISOString(),
        };
        mockRoles.push(newRole);

        res.json({
            success: true,
            message: '新增成功',
            result: newRole,
        });
    },

    // 编辑角色
    'PUT /sys/role/edit': async (req: any, res: any) => {
        await waitTime(500);
        const data = req.body;
        const index = mockRoles.findIndex(r => r.id === data.id);

        if (index > -1) {
            // 检查唯一性 (排除自己) (Mock)
            if (mockRoles.some((r, i) => r.roleCode === data.roleCode && i !== index)) {
                res.status(400).json({
                    success: false,
                    message: '角色编码已存在',
                });
                return;
            }

            mockRoles[index] = { ...mockRoles[index], ...data, updateTime: new Date().toISOString() };

            res.json({
                success: true,
                message: '编辑成功',
                result: mockRoles[index],
            });
        } else {
            res.status(404).json({
                success: false,
                message: '未找到角色',
            });
        }
    },

    // 获取所有角色 (通常用于下拉选择等)
    'GET /sys/role/queryall': async (req: any, res: any) => {
        await waitTime(300);
        res.json({
            success: true,
            message: '获取成功',
            result: mockRoles,
        });
    },

    // 检查角色编码唯一性 (如果需要)
    'POST /sys/role/checkCode': async (req: any, res: any) => {
        await waitTime(300);
        const { fieldVal, dataId } = req.body; // 假设后端API是检查roleCode
        const isDuplicate = mockRoles.some(r => r.roleCode === fieldVal && r.id !== dataId);

        res.json({
            success: !isDuplicate,
            message: isDuplicate ? '角色编码已存在' : '角色编码可用',
        });
    },
};